<script setup lang="ts">
// 编辑视频弹窗
import { computed, ref, watch } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { useDialog } from 'naive-ui';
import { msgCheckAction, updateCatalogAction } from '@/service/api';
import { successMessage } from '@/utils/utils';
import { localStg } from '@/utils/storage';

interface Props {
  show: boolean;
  catalogObj?: any;
}

const props = withDefaults(defineProps<Props>(), {
  show: false
});

interface FormData {
  name: string;
}

const formData = ref<FormData>({
  name: ''
});

const formRef = ref<FormInst | null>(null);

// 校验规则
const rules: FormRules = {
  name: {
    required: true,
    message: '请输入章节名称',
    trigger: ['input', 'blur']
  }
};

const emit = defineEmits(['update:show', 'saveParagraphName']);

const modalShowValue = computed({
  get() {
    return props.show;
  },
  set(value: boolean) {
    emit('update:show', value);
  }
});

watch(
  () => props.show,
  value => {
    if (value) {
      formData.value.name = props.catalogObj?.title;
    }
  }
);

// 取消
function closeModal() {
  console.log('close');
  modalShowValue.value = false;
}

const dialog = useDialog();

// 确认
function saveClick() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: formData.value.name
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `章节名称中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      const params: any = {
        id: props.catalogObj?.id,
        title: formData.value.name, // 标题
        logId: props.catalogObj?.logId,
        parentId: props.catalogObj?.parentId
      };
      const { data, error } = await updateCatalogAction(params);
      console.log('data: ', data);
      if (!error) {
        emit('saveParagraphName');
        successMessage('修改成功');
        closeModal();
      }
    }
  });
}
</script>

<template>
  <NModal
    v-model:show="modalShowValue"
    preset="card"
    title="请修改章节名称"
    class="w-640px"
    :mask-closable="false"
    @close="closeModal"
  >
    <NForm ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="auto">
      <NFormItem path="name">
        <NInput v-model:value="formData.name" type="text" placeholder="请输入章节名称" clearable />
      </NFormItem>
    </NForm>
    <template #footer>
      <NSpace class="w-full" :size="24" justify="end">
        <NButton class="w-72px" @click="closeModal">取消</NButton>
        <NButton class="w-72px" type="primary" @click="saveClick">确定</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
